package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

import cn.hutool.core.util.IdcardUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.bean.BeanUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.CheckInConfigDto;
import com.zzyl.nursing.dto.CheckInElderDto;
import com.zzyl.nursing.dto.ElderFamilyDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.util.CodeGenerator;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 入住Service业务层处理
 * 
 * @author alexis
 * @date 2025-09-30
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService
{
    @Autowired
    private CheckInMapper checkInMapper;

    @Autowired
    private ElderMapper elderMapper;

    @Autowired
    private BedMapper bedMapper;

    @Autowired
    private CheckInConfigMapper checkInConfigMapper;

    @Autowired
    private ContractMapper contractMapper;

    /**
     * 查询入住
     * 
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id)
    {
        return checkInMapper.selectById(id);
    }

    /**
     * 查询入住列表
     * 
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn)
    {
        return checkInMapper.insert(checkIn);
    }

    /**
     * 修改入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        return checkInMapper.updateById(checkIn);
    }

    /**
     * 批量删除入住
     * 
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return checkInMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除入住信息
     * 
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        return checkInMapper.deleteById(id);
    }

    /**
     * 新增入住
     * @param checkInApplyDto
     */
    @Override
    @Transactional
    public void apply(CheckInApplyDto checkInApplyDto) {
        //1.校验老人是否入住,如果已经入住，直接结束
        checkElderCheckIn(checkInApplyDto);

        //2.更新床位状态为已入住
        Bed bed = bedMapper.selectById(checkInApplyDto.getCheckInConfigDto().getBedId());
        bed.setBedStatus(1);
        bedMapper.updateBed(bed);

        //3.新增或更行老人信息
       Elder elder= insertOrUpdateElder(checkInApplyDto.getCheckInElderDto(),bed);

        //4.新增签约办理
        saveContract(checkInApplyDto,elder);

        //5.新增入住信息
       CheckIn checkIn = saveCheckIn( checkInApplyDto,elder,bed);
        //6.新增入住配置
        saveCheckInConfig( checkInApplyDto.getCheckInConfigDto(),checkIn);

    }

    /**
     * 查询入住详情
     * @param id
     * @return
     */
    @Override
    public CheckInDetailVo detail(Long id) {
        // 准备结果对象
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();
        // 1.设置入住配置响应信息
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        CheckIn checkIn = checkInMapper.selectById(id);
        BeanUtils.copyProperties(checkIn, checkInConfigVo);

        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(new LambdaQueryWrapper<CheckInConfig>().eq(CheckInConfig::getCheckInId, id));
        BeanUtils.copyProperties(checkInConfig, checkInConfigVo);

        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);

        // 2.设置老人响应信息
        CheckInElderVo checkInElderVo = new CheckInElderVo();
        // 获取老人ID
        Long elderId = checkIn.getElderId();
        Elder elder = elderMapper.selectById(elderId);
        BeanUtils.copyProperties(elder, checkInElderVo);
        // 从身份证号中获取老人的年龄
        checkInElderVo.setAge(IdcardUtil.getAgeByIdCard(elder.getIdCardNo()));
        checkInDetailVo.setCheckInElderVo(checkInElderVo);

        // 3.设置家属响应信息
        String remark = checkIn.getRemark();
        List<ElderFamilyVo> elderFamilyVos = JSON.parseArray(remark, ElderFamilyVo.class);
        checkInDetailVo.setElderFamilyVoList(elderFamilyVos);

        // 4.设置签约办理响应信息
        Contract contract = contractMapper.selectOne(new LambdaQueryWrapper<Contract>().eq(Contract::getElderId, elderId));
        checkInDetailVo.setContract(contract);

        // 5.返回结果
        return checkInDetailVo;
    }

    private void saveCheckInConfig(CheckInConfigDto checkInConfigDto, CheckIn checkIn) {
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(checkInConfigDto,checkInConfig);
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfigMapper.insertCheckInConfig(checkInConfig);

    }

    private CheckIn saveCheckIn(CheckInApplyDto checkInApplyDto, Elder elder, Bed bed) {
        CheckIn checkIn = new CheckIn();
        //插入入住信息
        checkIn.setElderId(elder.getId());
        checkIn.setElderName(elder.getName());
        checkIn.setIdCardNo(elder.getIdCardNo());
        //设置入住信息
        checkIn.setStartDate(checkInApplyDto.getCheckInConfigDto().getStartDate());
        checkIn.setEndDate(checkInApplyDto.getCheckInConfigDto().getEndDate());
        checkIn.setNursingLevelName(checkInApplyDto.getCheckInConfigDto().getNursingLevelName());
        checkIn.setBedNumber(bed.getBedNumber());

        //设置老人家属信息
        List<ElderFamilyDto> elderFamilyDtoList = checkInApplyDto.getElderFamilyDtoList();
        checkIn.setRemark(JSON.toJSONString(elderFamilyDtoList));
        //插入入住信息
        checkInMapper.insert(checkIn);
        return checkIn;

    }

    /**
     * 新增签约办理
     * @param checkInApplyDto
     * @param elder
     */
    private void saveContract(CheckInApplyDto checkInApplyDto, Elder elder) {
        Contract contract = new  Contract();
        //维护合同信息
        BeanUtils.copyProperties(checkInApplyDto.getCheckInContractDto(),contract);
        //老人信息
        contract.setElderId(elder.getId().intValue());
        contract.setContractName(elder.getName());
        contract.setElderName(elder.getName());
        contract.setStartDate(checkInApplyDto.getCheckInConfigDto().getStartDate());
        contract.setEndDate(checkInApplyDto.getCheckInConfigDto().getEndDate());
        //设置状态，如果开始时间小于当前时间，则设置状态为已生效
        if (LocalDateTime.now().isAfter(contract.getStartDate())){
            contract.setStatus(1);
        }
        //设置合同编号
        contract.setContractNumber("HT"+ CodeGenerator.generateContractNumber());
//插入合同
        contractMapper.insert(contract);
    }


    /**
     * 新增或更新老人信息
     * @param checkInElderDto
     * @param bed
     */
    private Elder insertOrUpdateElder(CheckInElderDto checkInElderDto, Bed bed) {
        //准备老人实体对象
        Elder elder = new Elder();
        BeanUtils.copyProperties(checkInElderDto,elder);
        //设置床位信息
        elder.setBedId(bed.getId());
        elder.setBedNumber(bed.getBedNumber());

        //查询老人信息
        Elder elderDb = elderMapper.selectOne(new LambdaQueryWrapper<Elder>().eq(Elder::getIdCardNo, checkInElderDto.getIdCardNo()));
        if (ObjectUtil.isNotNull(elderDb)){
            elder.setId(elderDb.getId());
            //如果老人纯在，更新
            elderMapper.updateElder(elder);
        }else  {
            //不存在就新增
            elderMapper.insert(elder);
        }
        return elder;


    }

    /**
     * 校验老人是否入住
     * @param checkInApplyDto
     */
    private void checkElderCheckIn(CheckInApplyDto checkInApplyDto) {
        LambdaQueryWrapper<Elder> elqw=new LambdaQueryWrapper<>();
        elqw.eq(Elder::getIdCardNo, checkInApplyDto.getCheckInElderDto().getIdCardNo());
        elqw.eq(Elder::getStatus,1);
        Elder elder = elderMapper.selectOne(elqw);
        if (ObjectUtil.isNotNull( elder)){
            //老人已入住
            throw new BaseException("该老人已入住");
        }
    }
}
